#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import os
import stat
import uuid

from oracle import logger
from common.common import execute_cmd, write_content_to_file
from oracle.common.constants import PluginPathConstant


class PowershellService(object):
    @staticmethod
    def exec_pw_shell(shell_cmd):
        filename = f'{uuid.uuid4()}.ps1'
        tmp_script = os.path.join(PluginPathConstant.WINDOWS_TMP_PATH + '/', filename)
        try:
            write_content_to_file(tmp_script, shell_cmd)
        except Exception as e_info:
            logger.info(f"e_info:{e_info}")
            return False, ''
        cmd = f'{PluginPathConstant.POWER_SHELL_PATH} {tmp_script}'
        logger.debug(f"cmd:{cmd}")
        ret, std_out, std_err = execute_cmd(cmd)
        os.remove(tmp_script)
        if int(ret) != 0:
            logger.error(f"exec_pw_shell cmd:{cmd} failed, {std_out}, {std_err}")
            return False, ''
        return True, std_out
